package com.github.leecho.ssc.config;

import com.github.leecho.ssc.captcha.authentication.CaptchaAuthenticationDetailsSource;
import com.github.leecho.ssc.captcha.authentication.CaptchaAuthenticationProvider;
import com.github.leecho.ssc.captcha.repository.CaptchaRepository;
import com.github.leecho.ssc.captcha.repository.impl.SessionCaptchaRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

import javax.servlet.http.HttpServletRequest;

/**
 * @author LIQIU
 * created on 2020/11/13
 **/
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Bean
    public CaptchaRepository<HttpServletRequest> sessionCaptchaRepository() {
        return new SessionCaptchaRepository();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/login")
                .loginPage("/login.html")
                .authenticationDetailsSource(new CaptchaAuthenticationDetailsSource(sessionCaptchaRepository()))
                .failureUrl("/login.html?error=true")
                .defaultSuccessUrl("/index.html")
                .and()
                .authenticationProvider(new CaptchaAuthenticationProvider())
                .csrf()
                .disable();
    }

    @Override
    public void configure(WebSecurity web) {
        web.ignoring()
                .mvcMatchers("/captcha", "/login.html");
    }
}
